import threading
from tkinter import Label, Button, Entry
from tkinter.ttk import Combobox

from util.comm.AsyncTask import AsyncTask
from util.comm.cmd_util import wrap_with_try_except
from util.env.java.jar_util import jarRun
from util.comm.msg_util import msg
import tkinter as tk

class WinJavaRunTool():
    def __init__(self):
        super().__init__()

    def menuFrame(self, tab, config):
        self.tab = tab
        data = config

        self.dropdown = Combobox(self.tab, width=10)

        self.jar_name = data['jar_name']
        self.url = data['url']
        config_list = data['configs']
        self.drop_list = []
        self.drop_config_list = []
        if isinstance(config_list, list):
            for index, c in enumerate(config_list):
                self.drop_list.append(c['name'])
                self.drop_config_list.append(c)
        else:
            print(data)
            msg('配置文件格式错误')
            return
        self.dropdown['values'] = self.drop_list
        self.dropdown.current(0)
        self.config = self.drop_config_list[0]
        self.dropdown.pack(side='right', fill='x', expand=False, anchor='ne', padx=5, pady=5)
        self.dropdown.bind("<<ComboboxSelected>>", self.select_item)
        ## 渲染窗口操作-输入框、按钮
        self.renderingBody()

    def renderingBody(self):
        if hasattr(self, 'menu'):
            self.menu.destroy()
        self.menu = tk.Frame(self.tab)
        self.menu.pack()

        c = self.config['params']

        params_list = []

        row = 0
        for value in c:
            self.label = Label(self.menu, text=value["name"], width=10)
            self.label.grid(row=row, column=1, padx=0, pady=5)
            self.Entry = Entry(self.menu, width=36)
            self.Entry.grid(row=row, column=2, padx=5, pady=5)
            self.Entry.insert(0, value["value"])
            params_list.append(self.Entry)
            new_row = tk.Frame(self.menu)
            new_row.grid(row=row, column=0, sticky='news')
            row += 1

        self.button = Button(self.menu, text="启动", command=lambda l=params_list: self.print_entry_sync(l))
        self.button.grid(row=row, column=2, padx=36, pady=5)

    def print_entry_sync(self, l):
        if hasattr(self, 'sync_flag') and self.sync_flag == '1':
            msg('正在处理,请勿重复操作')
            return
        self.sync_flag = '1'
        wrap_print_entry = wrap_with_try_except(self.print_entry)
        AsyncTask(threading.Thread(target=wrap_print_entry, args=(l,)), lambda: self.reset_sync()).execute_async()

    def reset_sync(self):
        self.sync_flag = '0'

    def print_entry(self, l):
        params = []
        if isinstance(l, list):
            for index, c in enumerate(l):
                if index == 5:
                    self.url = f'http://127.0.0.1:%s' % c.get()
                params.append(c.get())
        jarRun(self.jar_name, params, self.url)

    def select_item(self, event):
        index = self.dropdown.current()
        print('select_item----%s' % index)
        self.config = self.drop_config_list[index]
        self.renderingBody()


